//
//  HelloWorldLayer.mm
//  BlockGame
//
//  Created by weixian he on 12-11-3.
//  Copyright 广州从兴电子开发有限公司 2012年. All rights reserved.
//

// Import the interfaces
#import "HelloWorldLayer.h"
#import "DataModel.h"
#import "GameHUD.h"
#import "Tower.h"

#define kDisappearLine 20

// Needed to obtain the Navigation Controller
#import "AppDelegate.h"

#import "PhysicsSprite.h"
#import "MyContactListener.h"

enum {
	kTagParentNode = 1,
};


#pragma mark - HelloWorldLayer

@interface HelloWorldLayer()
{
    float mMaxY;
    int mTestSpace;
    b2Body* mGroundBody;
    MyContactListener *_contactListener;
    b2ContactFilter *_b2ContactFilter;
}
-(void) initPhysics;
-(void) addNewSpriteAtPosition:(CGPoint)p;
-(void) createMenu;
@end

@implementation HelloWorldLayer

+(CCScene *) scene
{
	// 'scene' is an autorelease object.
	CCScene *scene = [CCScene node];
	
	// 'layer' is an autorelease object.
	HelloWorldLayer *layer = [HelloWorldLayer node];
    DataModel *m = [DataModel getModel];
    m._gameLayer = layer;
    
    GameHUD *hud = [GameHUD sharedHUD];
    m._gameHUDLayer = hud;
    
    
    
    CCLayerColor *back = [[[CCLayerColor alloc] initWithColor:ccc4(100, 0, 0, 255)] autorelease];
	
	// add layer as a child to scene
    [scene addChild:back];
	[scene addChild: layer];

    [scene addChild:hud];
	
	// return the scene
	return scene;
}

-(id) init
{
	if( (self=[super init])) {
		
        mMaxY = 0.0;
        mTestSpace = 0;
		// enable events
		
		self.isTouchEnabled = YES;
		self.isAccelerometerEnabled = YES;
		CGSize s = [CCDirector sharedDirector].winSize;
        CGSize size = s;
		
		// init physics
		[self initPhysics];
		
		// create reset button
		[self createMenu];
		
		//Set up sprite
		
#if 1
		// Use batch node. Faster
		CCSpriteBatchNode *parent = [CCSpriteBatchNode batchNodeWithFile:@"blocks.png" capacity:100];
		spriteTexture_ = [parent texture];
#else
		// doesn't use batch node. Slower
		spriteTexture_ = [[CCTextureCache sharedTextureCache] addImage:@"blocks.png"];
		CCNode *parent = [CCNode node];
#endif
		[self addChild:parent z:0 tag:kTagParentNode];
		
		
        
        int total = 32768-1; //2^13-1
       
        
        int m = CCRANDOM_MINUS1_1() * total;
        NSLog(@"totoal = %d m= %d",total,m);
        int i;
        NSMutableArray *array = [[[NSMutableArray alloc] init] autorelease];
        while (1) {
            i = m %2;
            [array addObject:[NSString stringWithFormat:@"%d",i]];
            m = m/2;
            NSLog(@"m = %d",m);
            if(m == 1)
            {
                [array addObject:[NSString stringWithFormat:@"%d",m]];
                break;
            }
        }
        
        int count = array.count - 13;
        for( int i = 0; i< count; i++)
        {
            [array addObject:@"0"];
        }
        
        for(int i = 0 ; i < array.count; i++)
        {
            //NSLog(@"%@",s);
            NSString *s = [array objectAtIndex:i];
            if([s isEqualToString:@"1"])
            {
                [self addNewSpriteAtPosition:ccp(280 - i * 32, 16) isFirm:YES];
            }
        }
        
        /*
        [self addNewSpriteAtPosition:ccp(s.width/2, 32 + 16) isFirm:YES];
		[self addNewSpriteAtPosition:ccp(s.width/2, 16) isFirm:YES];
        
        [self addNewSpriteAtPosition:ccp(s.width/2 - 50, 16) isFirm:YES];
        
        [self addNewSpriteAtPosition:ccp(s.width/2 + 50, 16) isFirm:YES];
        [self addNewSpriteAtPosition:ccp(s.width/2 + 100,16) isFirm:YES];
         */
		
		CCLabelTTF *label = [CCLabelTTF labelWithString:@"Tap screen" fontName:@"Marker Felt" fontSize:32];
		[self addChild:label z:0];
		[label setColor:ccc3(0,0,255)];
		label.position = ccp( s.width/2, s.height-50);
		
        
        
        [[CCTextureCache sharedTextureCache] addImage: @"particle_fire.png"]; 
        //添加一个粒子特效
        CCParticleSystem *tempSystem = [ARCH_OPTIMAL_PARTICLE_SYSTEM particleWithFile:@"bottom_fire.plist"];
        //tempSystem.positionType=kCCPositionTypeRelative;//备注1
        tempSystem.positionType=kCCPositionTypeFree;
        tempSystem.position=ccp(160,0);
        [self addChild:tempSystem];
    
        
        [self initSound];
        
        CCLabelTTF *labelnum1 = [CCLabelTTF labelWithString:@"3" fontName:@"Marker Felt" fontSize:64];
        labelnum1.position =  ccp( size.width /2 , size.height/2 );
        [self addChild: labelnum1];
        
        CCLabelTTF *labelnum2 = [CCLabelTTF labelWithString:@"2" fontName:@"Marker Felt" fontSize:64];
        labelnum2.position =  ccp( size.width /2 , size.height/2 );
        labelnum2.visible = NO;
        [self addChild: labelnum2];
        
        CCLabelTTF *labelnum3 = [CCLabelTTF labelWithString:@"1" fontName:@"Marker Felt" fontSize:64];
        labelnum3.position =  ccp( size.width /2 , size.height/2 );
        labelnum3.visible = NO;
        [self addChild: labelnum3];
        
        CCLabelTTF *labelnum4 = [CCLabelTTF labelWithString:@"GO" fontName:@"Marker Felt" fontSize:64];
        labelnum4.position =  ccp( size.width /2 , size.height/2 );
        labelnum4.visible = NO;
        [self addChild: labelnum4];
        
        id ac  = [labelnum1 runAction:[CCShow action]];
        id ac0 = [labelnum1 runAction:[CCScaleBy actionWithDuration:0.5 scale:2]];
        id ac1 = [labelnum1 runAction:[CCHide action]];
        id ac2 = [labelnum2 runAction:[CCShow action]];
        id ac3 = [labelnum2 runAction:[CCScaleBy actionWithDuration:0.5 scale:2]];
        id ac4 = [labelnum2 runAction:[CCHide action]];
        id ac5 = [labelnum3 runAction:[CCShow action]];
        id ac6 = [labelnum3 runAction:[CCScaleBy actionWithDuration:0.5 scale:2]];
        id ac7 = [labelnum3 runAction:[CCHide action]];
        id ac8 = [labelnum4 runAction:[CCShow action]];
        id ac9 = [labelnum4 runAction:[CCScaleBy actionWithDuration:0.5 scale:2]];
        id ac10= [labelnum4 runAction:[CCHide action]];
        [labelnum1 runAction:[CCSequence actions:[CCDelayTime actionWithDuration:0.5], ac , ac0, ac1, nil]];
        [labelnum2 runAction:[CCSequence actions:[CCDelayTime actionWithDuration:1.0], ac2, ac3, ac4, nil]];
        [labelnum3 runAction:[CCSequence actions:[CCDelayTime actionWithDuration:1.5], ac5, ac6, ac7, nil]];
        [labelnum4 runAction:[CCSequence actions:[CCDelayTime actionWithDuration:2.0], ac8, ac9, ac10, nil]];
        
        
        
		[self scheduleUpdate];
	}
	return self;
}

-(void) dealloc
{
	delete world;
	world = NULL;
	
	delete m_debugDraw;
	m_debugDraw = NULL;
    
    delete _contactListener;
    _contactListener = NULL;
    
    delete _b2ContactFilter;
    _b2ContactFilter = NULL;
    
	[super dealloc];
}	


- (void)initSound
{
	[[SimpleAudioEngine sharedEngine] setBackgroundMusicVolume:0.3f];
	[[SimpleAudioEngine sharedEngine] playBackgroundMusic:@"back1.mp3" loop:NO];
	[[CDAudioManager sharedManager] setBackgroundMusicCompletionListener:self selector:@selector(soundFinish1)];
}

- (void)soundFinish1
{
	[[SimpleAudioEngine sharedEngine] pauseBackgroundMusic];
	[[SimpleAudioEngine sharedEngine] playBackgroundMusic:@"back2.mp3" loop:NO];
	[[CDAudioManager sharedManager] setBackgroundMusicCompletionListener:self selector:@selector(soundFinish2)];
}

- (void)soundFinish2
{
	[[SimpleAudioEngine sharedEngine] pauseBackgroundMusic];
	[[SimpleAudioEngine sharedEngine] playBackgroundMusic:@"back3.mp3" loop:NO];
	[[CDAudioManager sharedManager] setBackgroundMusicCompletionListener:self selector:@selector(soundFinish1)];
}

-(void) createMenu
{
	// Default font size will be 22 points.
	[CCMenuItemFont setFontSize:22];
	
	// Reset Button
	CCMenuItemLabel *reset = [CCMenuItemFont itemWithString:@"Reset" block:^(id sender){
        mTestSpace = mTestSpace + 40;
   
        
       
        // Define the ground body.
        b2BodyDef groundBodyDef;
        groundBodyDef.position.Set(0, 0); // bottom-left corner
        
        // Call the body factory which allocates memory for the ground body
        // from a pool and creates the ground box shape (also from a pool).
        // The body is also added to the world.
        world->DestroyBody(mGroundBody);
        mGroundBody = world->CreateBody(&groundBodyDef);
        
        // Define the ground box shape.
        b2EdgeShape groundBox;
        
        CGSize s = [[CCDirector sharedDirector] winSize];
        
        float ySpace = 70.0;
        //float height = s.height - ySpace;
        float height = 300 + mTestSpace;
        // bottom
        
        groundBox.Set(b2Vec2(0,0), b2Vec2(s.width/PTM_RATIO,0));
        mGroundBody->CreateFixture(&groundBox,0);
        
        // top
        groundBox.Set(b2Vec2(0,height/PTM_RATIO), b2Vec2(s.width/PTM_RATIO,height/PTM_RATIO));
        mGroundBody->CreateFixture(&groundBox,0);
        
        // left
        groundBox.Set(b2Vec2(0,height/PTM_RATIO), b2Vec2(0,0));
        mGroundBody->CreateFixture(&groundBox,0);
        
        // right
        groundBox.Set(b2Vec2(s.width/PTM_RATIO,height/PTM_RATIO), b2Vec2(s.width/PTM_RATIO,0));
        mGroundBody->CreateFixture(&groundBox,0);
        
		//[[CCDirector sharedDirector] replaceScene: [HelloWorldLayer scene]];
	}];
	
	// Achievement Menu Item using blocks
	CCMenuItem *itemAchievement = [CCMenuItemFont itemWithString:@"Achievements" block:^(id sender) {
		
		 CCDirector *director_ = (CCDirectorIOS*) [CCDirector sharedDirector];
        [director_.navigationController popViewControllerAnimated:YES];
       
        return;
		GKAchievementViewController *achivementViewController = [[GKAchievementViewController alloc] init];
		achivementViewController.achievementDelegate = self;
		
		AppController *app = (AppController*) [[UIApplication sharedApplication] delegate];
		
		[[app navController] presentModalViewController:achivementViewController animated:YES];
	}];
	
	// Leaderboard Menu Item using blocks
	CCMenuItem *itemLeaderboard = [CCMenuItemFont itemWithString:@"Leaderboard" block:^(id sender) {
		
		
		GKLeaderboardViewController *leaderboardViewController = [[GKLeaderboardViewController alloc] init];
		leaderboardViewController.leaderboardDelegate = self;
		
		AppController *app = (AppController*) [[UIApplication sharedApplication] delegate];
		
		[[app navController] presentModalViewController:leaderboardViewController animated:YES];
	}];
	
	CCMenu *menu = [CCMenu menuWithItems:itemAchievement, itemLeaderboard, reset, nil];
	
	[menu alignItemsVertically];
	
	CGSize size = [[CCDirector sharedDirector] winSize];
	[menu setPosition:ccp( size.width/2, size.height/2)];
	
	
	[self addChild: menu z:-1];	
}

-(void) initPhysics
{
	
	CGSize s = [[CCDirector sharedDirector] winSize];
	
	b2Vec2 gravity;
	gravity.Set(0.0f, -10.0f);
	world = new b2World(gravity);
	
	
	// Do we want to let bodies sleep?
	world->SetAllowSleeping(true);
	
	world->SetContinuousPhysics(true);
	
	//m_debugDraw = new GLESDebugDraw( PTM_RATIO );
	//world->SetDebugDraw(m_debugDraw);
	
	uint32 flags = 0;
	flags += b2Draw::e_shapeBit;
	//		flags += b2Draw::e_jointBit;
	//		flags += b2Draw::e_aabbBit;
	//		flags += b2Draw::e_pairBit;
	//		flags += b2Draw::e_centerOfMassBit;
	//m_debugDraw->SetFlags(flags);
	
	
	// Define the ground body.
	b2BodyDef groundBodyDef;
	groundBodyDef.position.Set(0, 0); // bottom-left corner
	
	// Call the body factory which allocates memory for the ground body
	// from a pool and creates the ground box shape (also from a pool).
	// The body is also added to the world.
	mGroundBody = world->CreateBody(&groundBodyDef);
	
	// Define the ground box shape.
	b2EdgeShape groundBox;		
	
    float ySpace = 70.0;
    //float height = s.height - ySpace;
    float height = 0;
	// bottom
	
	groundBox.Set(b2Vec2(0,0), b2Vec2(s.width/PTM_RATIO,0));
	mGroundBody->CreateFixture(&groundBox,0);
	
	// top
	groundBox.Set(b2Vec2(0,height/PTM_RATIO), b2Vec2(s.width/PTM_RATIO,height/PTM_RATIO));
	mGroundBody->CreateFixture(&groundBox,0);
	
	// left
	groundBox.Set(b2Vec2(0,height/PTM_RATIO), b2Vec2(0,0));
	mGroundBody->CreateFixture(&groundBox,0);
	
	// right
	groundBox.Set(b2Vec2(s.width/PTM_RATIO,height/PTM_RATIO), b2Vec2(s.width/PTM_RATIO,0));
	mGroundBody->CreateFixture(&groundBox,0);
    
    // Create contact listener
    _contactListener = new MyContactListener();
    world->SetContactListener(_contactListener);
    
    _b2ContactFilter = new b2ContactFilter();
    world->SetContactFilter(_b2ContactFilter);
    
    
}

-(b2World *)getYWorld
{
    return world;
}


/*
-(void) draw
{
	//
	// IMPORTANT:
	// This is only for debug purposes
	// It is recommend to disable it
	//
	[super draw];
	
    
	ccGLEnableVertexAttribs( kCCVertexAttribFlag_Position );
	
	kmGLPushMatrix();
	
	world->DrawDebugData();	
	
	kmGLPopMatrix();
     
    
}
*/

-(void) addNewSpriteAtPosition:(CGPoint)p isFirm:(BOOL)isFirm
{
	CCLOG(@"Add sprite %0.2f x %02.f",p.x,p.y);
	CCNode *parent = [self getChildByTag:kTagParentNode];
	
	//We have a 64x64 sprite sheet with 4 different 32x32 images.  The following code is
	//just randomly picking one of the images
	int idx = (CCRANDOM_0_1() > .5 ? 0:1);
	int idy = (CCRANDOM_0_1() > .5 ? 0:1);
	PhysicsSprite *sprite = [PhysicsSprite spriteWithTexture:spriteTexture_ rect:CGRectMake(32 * idx,32 * idy,32,32)];
    sprite.type = FirmType;
	[parent addChild:sprite];
	
    sprite.opacity = 80;
	sprite.position = ccp( p.x, p.y);
	
	// Define the dynamic body.
	//Set up a 1m squared box in the physics world
	b2BodyDef bodyDef;
    if(isFirm == NO)
    {
        bodyDef.type = b2_dynamicBody;
    }
    else
    {
        bodyDef.type = b2_staticBody;
    }
	
	bodyDef.position.Set(p.x/PTM_RATIO, p.y/PTM_RATIO);
	b2Body *body = world->CreateBody(&bodyDef);
	
	// Define another box shape for our dynamic body.
	b2PolygonShape dynamicBox;
	dynamicBox.SetAsBox(.5f, .5f);//These are mid points for our 1m box
	
	// Define the dynamic body fixture.
	b2FixtureDef fixtureDef;
	fixtureDef.shape = &dynamicBox;
	fixtureDef.density = 1.0f;
	fixtureDef.friction = 0.3f;
	body->CreateFixture(&fixtureDef);
    
	
	[sprite setPhysicsBody:body];
}

-(void) addNewSpriteAtPosition:(CGPoint)p
{
	CCLOG(@"Add sprite %0.2f x %02.f",p.x,p.y);
	//CCNode *parent = [self getChildByTag:kTagParentNode];
	
	//We have a 64x64 sprite sheet with 4 different 32x32 images.  The following code is
	//just randomly picking one of the images
	/*
    int idx = (CCRANDOM_0_1() > .5 ? 0:1);
	int idy = (CCRANDOM_0_1() > .5 ? 0:1);
	PhysicsSprite *sprite = [PhysicsSprite spriteWithTexture:spriteTexture_ rect:CGRectMake(32 * idx,32 * idy,32,32)];
    */
    
    PhysicsSprite *sprite = [PhysicsSprite spriteWithFile:@"zheng_fang_xing.png" rect:CGRectMake(0, 0, 48, 48)];
    
    sprite.type = YSpaceType;
    [self addChild:sprite];
	//[parent addChild:sprite];
	
	sprite.position = ccp( p.x, p.y);
    
    
	
	// Define the dynamic body.
	//Set up a 1m squared box in the physics world
	b2BodyDef bodyDef;
	bodyDef.type = b2_dynamicBody;
	bodyDef.position.Set(p.x/PTM_RATIO, p.y/PTM_RATIO);
	b2Body *body = world->CreateBody(&bodyDef);
	
	// Define another box shape for our dynamic body.
	b2PolygonShape dynamicBox;
	dynamicBox.SetAsBox(48.0/32.0/2, 48.0/32.0/2);//These are mid points for our 1m box
	
	// Define the dynamic body fixture.
	b2FixtureDef fixtureDef;
	fixtureDef.shape = &dynamicBox;	
	fixtureDef.density = 1.0f;
	fixtureDef.friction = 0.3f;
	body->CreateFixture(&fixtureDef);
    
    
  
	/*
     b2BodyDef spriteBodyDef;
     spriteBodyDef.type = b2_dynamicBody;
     spriteBodyDef.position.Set(sprite.position.x/PTM_RATIO, sprite.position.y/PTM_RATIO);
     spriteBodyDef.userData = sprite;
     b2Body *spriteBody = _world->CreateBody(&spriteBodyDef);
     
     b2PolygonShape spriteShape;
     //spriteShape.SetAsBox(sprite.contentSize.width/PTM_RATIO/2,sprite.contentSize.height/PTM_RATIO/2);
    if (sprite.tag == 1) {
        int num = 6;
        b2Vec2 verts[] = {b2Vec2(4.5f / PTM_RATIO, -17.7f / PTM_RATIO),
            b2Vec2(20.5f / PTM_RATIO, 7.2f / PTM_RATIO),
            b2Vec2(22.8f / PTM_RATIO, 29.5f / PTM_RATIO),
            b2Vec2(-24.7f / PTM_RATIO, 31.0f / PTM_RATIO),
            b2Vec2(-20.2f / PTM_RATIO, 4.7f / PTM_RATIO),
            b2Vec2(-11.7f / PTM_RATIO, -17.5f / PTM_RATIO)};
        spriteShape.Set(verts, num);
    } else {
        // Do the same thing as the above, but use the car data this time
        int num = 7;
        b2Vec2 verts[] = {b2Vec2(-11.8f / PTM_RATIO, -24.5f / PTM_RATIO),
            b2Vec2(11.7f / PTM_RATIO, -24.0f / PTM_RATIO),
            b2Vec2(29.2f / PTM_RATIO, -14.0f / PTM_RATIO),
            b2Vec2(28.7f / PTM_RATIO, -0.7f / PTM_RATIO),
            b2Vec2(8.0f / PTM_RATIO, 18.2f / PTM_RATIO),
            b2Vec2(-29.0f / PTM_RATIO, 18.7f / PTM_RATIO),
            b2Vec2(-26.3f / PTM_RATIO, -12.2f / PTM_RATIO)};
        spriteShape.Set(verts, num);
    }
    
    b2FixtureDef spriteShapeDef;
    spriteShapeDef.shape = &spriteShape;
    spriteShapeDef.density = 10.0;
    spriteShapeDef.isSensor = true;
    
    spriteBody->CreateFixture(&spriteShapeDef);
     */
    
	[sprite setPhysicsBody:body];
}

// convenience method to convert a CGPoint to a b2Vec2
-(b2Vec2) toMeters:(CGPoint)point
{
	return b2Vec2(point.x / PTM_RATIO, point.y / PTM_RATIO);
}

// convenience method to convert a b2Vec2 to a CGPoint
-(CGPoint) toPixels:(b2Vec2)vec
{
	return ccpMult(CGPointMake(vec.x, vec.y), PTM_RATIO);
}

-(void) update: (ccTime) dt
{
    
    
     //It is recommended that a fixed time step is used with Box2D for stability
     //of the simulation, however, we are using a variable time step here.
     //You need to make an informed choice, the following URL is useful
     //http://gafferongames.com/game-physics/fix-your-timestep/
     
     int32 velocityIterations = 8;
     int32 positionIterations = 1;
     
     // Instruct the world to perform a single step of simulation. It is
     // generally best to keep the time step and iterations fixed.
     world->Step(dt, velocityIterations, positionIterations);
    
    
    
    std::vector<MyContact>::iterator pos;
    for(pos = _contactListener->_contacts.begin(); pos != _contactListener->_contacts.end(); ++pos) {
        MyContact contact = *pos;
        
        // Get the box2d bodies for each object
        b2Body *bodyA = contact.fixtureA->GetBody();
        b2Body *bodyB = contact.fixtureB->GetBody();
        if (bodyA->GetUserData() != NULL && bodyB->GetUserData() != NULL) {
            CCSprite *spriteA = (CCSprite *) bodyA->GetUserData();
            CCSprite *spriteB = (CCSprite *) bodyB->GetUserData();
            
            //b2Vec2 *vA =bodyA->GetLinearVelocity();
            //if(bodyA->m_linearVelocity)
            
            //[[SimpleAudioEngine sharedEngine] playEffect:@"disp1.wav"];
            /*
            // Is sprite A a cat and sprite B a car?  If so, push the cat on a list to be destroyed...
            if (spriteA.tag == 1 && spriteB.tag == 2) {
                toDestroy.push_back(bodyA);
            }
            // Is sprite A a car and sprite B a cat?  If so, push the cat on a list to be destroyed...
            else if (spriteA.tag == 2 && spriteB.tag == 1) {
                toDestroy.push_back(bodyB);
            }
            */
        }
    }
    
    
     // for each body, get its assigned sprite and update the sprite's position
    int maxY = 0;
     for (b2Body* body = world->GetBodyList(); body != nil; body = body->GetNext())
     {
         PhysicsSprite* sprite = (PhysicsSprite*)body->GetUserData();
         if (sprite != NULL)
         {
         // update the sprite's position to where their physics bodies are
             sprite.position = [self toPixels:body->GetPosition()];
             float angle = body->GetAngle();
             sprite.rotation = CC_RADIANS_TO_DEGREES(angle) * -1;
             
             maxY = MAX(maxY, (int)sprite.position.y);
             //[[SimpleAudioEngine sharedEngine] playEffect:@"disp1.wav"];
             if(sprite.position.y < kDisappearLine && sprite.type != FirmType)
             {
                 [[SimpleAudioEngine sharedEngine] playEffect:@"disp1.wav"];
                 CCNode *parent = [self getChildByTag:kTagParentNode];
                 world->DestroyBody([sprite getPhysicsBody]);
                 //[parent removeChild:sprite cleanup:YES];
                 [self removeChild:sprite cleanup:YES];
             }
         }
     }
    
    CCLOG(@"maxY = %d",maxY);

}



- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
	//Add a new body/atlas sprite at the touched location
	for( UITouch *touch in touches ) {
		CGPoint location = [touch locationInView: [touch view]];
		
		location = [[CCDirector sharedDirector] convertToGL: location];
		
		[self addNewSpriteAtPosition: location];
	}
}


- (BOOL) canBuildOnTilePosition:(CGPoint) pos 
{
    
    return YES;
    /*
	CGPoint towerLoc = [self tileCoordForPosition: pos];
	
	int tileGid = [self.background tileGIDAt:towerLoc];
	NSDictionary *props = [self.tileMap propertiesForGID:tileGid];
	NSString *type = [props valueForKey:@"buildable"];
	
	if([type isEqualToString: @"1"]) {
		return YES;
	}
	
	return NO;
    */
}

- (CGPoint) tileCoordForPosition:(CGPoint) position 
{
    /*
	int x = position.x / self.tileMap.tileSize.width;
	int y = ((self.tileMap.mapSize.height * self.tileMap.tileSize.height) - position.y) / self.tileMap.tileSize.height;
	
	return ccp(x,y);
     */
    
    return position;
}

-(void)addTower: (CGPoint)pos {
    
    
    [self addNewSpriteAtPosition:pos];
    /*
    Tower *target = [MachineGunTower tower];
    target.position = pos;
    [self addChild:target z:1];
     */
    
    /*
	DataModel *m = [DataModel getModel];
	
	Tower *target = nil;
	
	CGPoint towerLoc = [self tileCoordForPosition: pos];
	
	int tileGid = [self.background tileGIDAt:towerLoc];
	NSDictionary *props = [self.tileMap propertiesForGID:tileGid];
	NSString *type = [props valueForKey:@"buildable"];
	
	
	NSLog(@"Buildable: %@", type);
	if([type isEqualToString: @"1"]) {
		target = [MachineGunTower tower];
		target.position = ccp((towerLoc.x * 32) + 16, self.tileMap.contentSize.height - (towerLoc.y * 32) - 16);
		[self addChild:target z:1];
		
		target.tag = 1;
		[m._towers addObject:target];
		
	} else {
		NSLog(@"Tile Not Buildable");
	}
     */
	
}

- (CGPoint)boundLayerPos:(CGPoint)newPos {
    /*
    CGSize winSize = [CCDirector sharedDirector].winSize;
    CGPoint retval = newPos;
    retval.x = MIN(retval.x, 0);
    retval.x = MAX(retval.x, -_tileMap.contentSize.width+winSize.width); 
    retval.y = MIN(0, retval.y);
    retval.y = MAX(-_tileMap.contentSize.height+winSize.height, retval.y); 
    return retval;
     */
    
    
    
    CGSize winSize = [CCDirector sharedDirector].winSize;
    CGPoint retval = newPos;
    float mapWidth=320.0;
    float mapHeight = 500.0*2;
    retval.x = MIN(retval.x, 0);
    retval.x = MAX(retval.x, -mapWidth+winSize.width); 
    retval.y = MIN(0, retval.y);
    retval.y = MAX(-mapHeight+winSize.height, retval.y);  
    return retval;
}

- (void)handlePanFrom:(UIPanGestureRecognizer *)recognizer {
    
    return;
    
    if (recognizer.state == UIGestureRecognizerStateBegan) {    
        
        CGPoint touchLocation = [recognizer locationInView:recognizer.view];
        touchLocation = [[CCDirector sharedDirector] convertToGL:touchLocation];
        touchLocation = [self convertToNodeSpace:touchLocation];                
        
    } else if (recognizer.state == UIGestureRecognizerStateChanged) {    
        
        CGPoint translation = [recognizer translationInView:recognizer.view];
        translation = ccp(translation.x, -translation.y);
        CGPoint newPos = ccpAdd(self.position, translation);
        self.position = [self boundLayerPos:newPos];  
        [recognizer setTranslation:CGPointZero inView:recognizer.view];    
        
    } else if (recognizer.state == UIGestureRecognizerStateEnded) {
        
		float scrollDuration = 0.2;
		CGPoint velocity = [recognizer velocityInView:recognizer.view];
		CGPoint newPos = ccpAdd(self.position, ccpMult(ccp(velocity.x, velocity.y * -1), scrollDuration));
		newPos = [self boundLayerPos:newPos];
        
		[self stopAllActions];
		CCMoveTo *moveTo = [CCMoveTo actionWithDuration:scrollDuration position:newPos];            
		[self runAction:[CCEaseOut actionWithAction:moveTo rate:1]]; 
        
        
    
        
    }        
}

#pragma mark GameKit delegate

-(void) achievementViewControllerDidFinish:(GKAchievementViewController *)viewController
{
	AppController *app = (AppController*) [[UIApplication sharedApplication] delegate];
	[[app navController] dismissModalViewControllerAnimated:YES];
}

-(void) leaderboardViewControllerDidFinish:(GKLeaderboardViewController *)viewController
{
	AppController *app = (AppController*) [[UIApplication sharedApplication] delegate];
	[[app navController] dismissModalViewControllerAnimated:YES];
}

@end
